package com.estar.assistsurvy.activity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import com.estar.assistsurvy.R;
import com.estar.assistsurvy.adapter.HistoryListAdapter;
import com.estar.assistsurvy.entity.HistoricalCase;
import com.estar.assistsurvy.entity.RequestHistory;
import com.estar.assistsurvy.entity.ResponseHistory;
import com.estar.assistsurvy.thread.HistoryCaseThread;
import com.estar.assistsurvy.utils.ExitUtils;
import com.estar.assistsurvy.utils.MightypleUtil;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class HistoryActivity extends BaseActivity implements OnClickListener,OnItemClickListener,OnRefreshListener{

	private LinearLayout returnBack;
	private EditText carNum;
	private TextView startDate,stopDate;
	private Button queryTask;
	private SwipeRefreshLayout id_swipe_ly;
	private ListView id_listview;
	private InputMethodManager imm;
	private Calendar calendar;
	private String uuid,deviceUUID,targetCar="",startTime="",endTime="";
	private SharedPreferences preference;
	private Intent intent;
	private List<HistoricalCase> historicalCasesList;
	private HistoryListAdapter adapter;
	private ProgressDialog dialog;
	private Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(dialog!=null){
				dialog.dismiss();
			}
			switch (msg.what) {
			case -1:
				showShortToast((String) msg.obj);
				break;

			case 0:
				ResponseHistory history=new ResponseHistory();
				history=(ResponseHistory) msg.obj;
				if(history.getCode().equals("1")){
					historicalCasesList=new ArrayList<>();
					historicalCasesList=history.getHistoricalCasesList();
					if(historicalCasesList.size()==0||historicalCasesList==null){
						showShortToast("当前历史任务为空!");
					}
					adapter=new HistoryListAdapter(historicalCasesList, HistoryActivity.this);
					id_listview.setAdapter(adapter);
					id_swipe_ly.setRefreshing(false);

				}else if(history.getCode().equals("0")){
					showShortToast(history.getMessages());
				}else if(history.getCode().equals("2")){
					ExitUtils.Unlogin(HistoryActivity.this, history.getMessages());
				}
				break;

			default:
				break;
			}

		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_history);
		initView();
	}
	@SuppressWarnings("deprecation")
	private void initView(){
		returnBack=find(R.id.returnBack);
		returnBack.setOnClickListener(this);
		carNum=find(R.id.carNum);
		startDate=find(R.id.startDate);
		startDate.setOnClickListener(this);
		stopDate=find(R.id.stopDate);
		stopDate.setOnClickListener(this);
		queryTask=find(R.id.queryTask);
		queryTask.setOnClickListener(this);
		queryTask.requestFocus();

		id_listview=find(R.id.id_listview);
		id_listview.setDividerHeight(5);
		id_listview.setOnItemClickListener(this);
		id_swipe_ly=find(R.id.id_swipe_ly);
		id_swipe_ly.setOnRefreshListener(this);
		id_swipe_ly.setColorScheme(android.R.color.holo_green_dark, android.R.color.holo_green_light,
				android.R.color.holo_orange_light, android.R.color.holo_red_light);
		//		mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mDatas);
		//		mListView.setAdapter(mAdapter);
		id_swipe_ly.setRefreshing(true);


		imm=(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);


		calendar=Calendar.getInstance();
		preference=getSharedPreferences("user", Context.MODE_PRIVATE);
		uuid=preference.getString("uuid", "");
		deviceUUID=MightypleUtil.getDeviceId(HistoryActivity.this);
		getList();
	}

	private void getList() {
		dialog=ProgressDialog.show(this, null, "获取历史订单…", false, false);
		RequestHistory requestHistory=new RequestHistory(deviceUUID, uuid, targetCar, startTime, endTime);
		new HistoryCaseThread(HistoryActivity.this, handler, requestHistory).start();

	}

	// 隐藏软键盘
	private void hideKeyboard() {
		if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
			if (getCurrentFocus() != null)
				imm.hideSoftInputFromWindow(getCurrentFocus()
						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		//		imm.hideSoftInputFromWindow(v.getWindowToken(), 0); //强制隐藏键盘  
		hideKeyboard();
		switch (v.getId()) {
		case R.id.returnBack:
			finish();
			break;

		case R.id.startDate:
			new DatePickerDialog(HistoryActivity.this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {

				@Override
				public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
					// TODO Auto-generated method stub
					// 更新EditText控件日期 小于10加0
					startDate.setText(new StringBuilder()
							.append(year)
							.append("-")
							.append((month + 1) < 10 ? "0"
									+ (month + 1) : (month + 1))
							.append("-")
							.append((dayOfMonth < 10) ? "0" + dayOfMonth : dayOfMonth));
					stopDate.requestFocus();
				}
			}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
			break;

		case R.id.stopDate:
			new DatePickerDialog(HistoryActivity.this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {

				@Override
				public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
					// TODO Auto-generated method stub
					// 更新EditText控件日期 小于10加0
					stopDate.setText(new StringBuilder()
							.append(year)
							.append("-")
							.append((month + 1) < 10 ? "0"
									+ (month + 1) : (month + 1))
							.append("-")
							.append((dayOfMonth < 10) ? "0" + dayOfMonth : dayOfMonth));
					queryTask.requestFocus();
				}
			}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();

			break;

		case R.id.queryTask:
			targetCar=carNum.getText().toString().trim();
			startTime=startDate.getText().toString().trim();
			endTime=stopDate.getText().toString().trim();
			getList();
			break;

		default:
			break;
		}
	}
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// TODO Auto-generated method stub
		intent=new Intent(HistoryActivity.this, TaskDetailActivity.class);
		HistoricalCase historicalCase=historicalCasesList.get(position);
		intent.putExtra("historicalCase", historicalCase);
		startActivity(intent);
	}
	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		getList();
	}

}
